<template>
  <div v-loading="isLoading">
    <el-dialog v-model="showAdjustTime" width="600px" center :show-close="false">
      <template #header>
        <div class="header">
          <title-view title="调整任务计划" />
          <el-icon size="16px" style="cursor: pointer" @click="handleCancel"><Close /></el-icon>
        </div>
      </template>
      <div class="customer-info">{{ formData.customerName }}丨{{ formData.residence }} 丨{{ formData.taskName }}</div>
      <el-form class="plan-form" ref="formRef" :model="formData" :rules="formRule" label-width="150px">
        <el-form-item label="计划时间范围" prop="timeRange">
          <el-date-picker
            :disabled-date="disabledDate"
            v-model="formData.timeRange"
            type="daterange"
            range-separator="至"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="changeDate"
          />
        </el-form-item>
        <el-form-item label="计划工期" prop="executeDays">
          <el-input type="number" @input="changeDays" v-model="formData.executeDays" placeholder="请输入计划工期"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="userId">
          <select-remote
            v-model="formData.userId"
            @change-select="changeRoleSelect"
            @clear-select="clearSelect"
            placeholder="请输入负责人"
            :request-api="memberByRoleId"
            :optionList="currentDirectorList"
            :params="{ roleId: formData.roleId }"
            :defaultConfig="{ keyword: 'userName', label: 'nickName', value: 'userId' }"
          ></select-remote>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handleCancel">取消 </el-button>
          <el-button style="width: 92px" :disabled="isLoading" type="primary" @click="handleConfirm">确定并调整</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, getCurrentInstance } from "vue";
import { Close } from "@element-plus/icons-vue";
import { adjustPlanDetail, changeTime, submitAdjustTime, taskSubmitAdjustTime, memberByRoleId } from "@/apis/constructionPlan";
import { disabledDate } from "@/utils/disabledOldDate";
import { debounce } from "lodash";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentStageTaskId: {
    type: String,
    default: ""
  },
  fromPage: {
    type: String,
    default: ""
  }
});
const currentStageTaskId = props.currentStageTaskId;
const fromPage = props.fromPage;

const showAdjustTime = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
const emit = defineEmits(["update:modelValue", "adjustTimeSave"]);

//表单相关
const formData = ref({
  executeDays: "",
  userId: "",
  timeRange: []
});
const formRule = {
  timeRange: [{ required: true, message: "请选择计划时间范围", trigger: "change" }],
  executeDays: [
    { required: true, message: "请输入计划工期", trigger: "blur" },
    { validator: (rule, value, callback) => validatePositiveInteger(rule, value, callback), trigger: "blur" }
  ],
  userId: [{ required: true, message: "请选择负责人", trigger: "change" }]
};
const validatePositiveInteger = (rule, value, callback) => {
  value = Number(value);
  if (/^(([1-9]\d?)|(127))$/.test(value)) {
    callback();
  } else {
    callback("请输入正整数，正整数需小于128");
  }
};

//时间
const changeDate = async () => {
  const timeRange = formData.value.timeRange;
  const executeDays = Number(formData.value.executeDays);
  if (timeRange.length && /^(([1-9]\d?)|(127))$/.test(executeDays)) {
    const params = {
      stageTaskId: currentStageTaskId,
      plainStartDate: timeRange[0],
      plainEndDate: timeRange[1],
      executeDays: 0
    };
    const { data } = await changeTime(currentStageTaskId, params);
    console.log("data", data);
    formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
    formData.value.executeDays = data.executeDays;
  }
};
const changeDays = debounce(async () => {
  const timeRange = formData.value.timeRange;
  if (timeRange.length) {
    const params = {
      stageTaskId: currentStageTaskId,
      executeDays: formData.value.executeDays
    };
    const { data } = await changeTime(currentStageTaskId, params);
    console.log("data", data);
    formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
    formData.value.executeDays = data.executeDays;
  }
}, 800);

//负责人
const currentDirectorList = ref([]);
const changeRoleSelect = data => {
  const { deptId, deptName, nickName, userId } = data;
  formData.value.userId = userId;
  formData.value.userName = nickName;
  formData.value.deptId = deptId;
  formData.value.deptName = deptName;
};
const clearSelect = () => {
  formData.value.userId = "";
};

//详情
const getDetail = async () => {
  isLoading.value = true;
  const { data } = await adjustPlanDetail(currentStageTaskId);
  formData.value = data;
  formData.value.timeRange = [data.plainStartDate, data.plainEndDate];
  currentDirectorList.value = [{ userId: data.userId, nickName: data.userName }];
  isLoading.value = false;
};

//按钮操作
const isLoading = ref(false);
const handleCancel = () => {
  showAdjustTime.value = false;
};
const handleConfirm = () => {
  proxy.$refs.formRef.validate(async valid => {
    if (!valid) return proxy.$modal.msgError("请完善信息");
    formData.value.plainStartDate = formData.value.timeRange[0];
    formData.value.plainEndDate = formData.value.timeRange[1];
    if (fromPage === "taskList") {
      await taskSubmitAdjustTime(formData.value);
    } else {
      await submitAdjustTime(formData.value);
    }

    isLoading.value = true;
    proxy.$modal.msgSuccess("计划调整成功");
    showAdjustTime.value = false;
    emit("adjustTimeSave");
  });
};

getDetail();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
.header {
  display: flex;
  justify-content: space-between;
}
.customer-info {
  color: #86909c;
  font-size: 14px;
  margin-bottom: 20px;
}
.plan-form {
  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner) {
    box-shadow: none;
  }
}
</style>
